const Router = require('@koa/router');
const router = new Router();
const { userLogin, register } = require('../controllers/index.js')
const { sign, verify, refreshVerify } = require('../utils/jwt.js');

// 路由前缀
router.prefix('/user')

router.get('/noteClass', (ctx) => {
    ctx.body = 'noteClass'
})

router.post('/login', async (ctx) => {
    // 获取请求体中的账号、密码
    // post 请求携带的参数都在请求体里的
    const { username, password } = ctx.request.body
    // 要去数据库中查询账号、密码是否正确
    try {
        let res = await userLogin(username, password)
        // console.log(res);
        // 数据库中查询账号、密码是否正确
        // 账号、密码正确，返回成功
        // 账号、密码错误，返回失败
        console.log("当前登录用户" + res[0].username);
        if (res.length) { // 找到了有数据
            let data = {
                id: res[0].id,
                username: res[0].username,
                password: res[0].password,
                create_time: res[0].create_time,
            }

            // 短token
            const access_token = sign(data, '1h');
            // 长token
            const refresh_token = sign(data, '7d');
            // // console.log(token);
            // const token = sign(data);

            ctx.body = {
                code: '1',
                msg: '登录成功',
                data: data,
                access_token: access_token,
                refresh_token: refresh_token,
                // token: token,
            }
        } else { // 逻辑性错误
            ctx.body = {
                code: '0',
                msg: '账号或密码错误',
                data: {}
            }
        }
    } catch (err) {
        ctx.body = {
            code: '-1',
            msg: '服务器异常',
            data: err.message
        }
    }

})


// verify()的返回是一个函数体
router.get('/test', verify(), async (ctx) => {
    console.log('测试接口被调用')
    ctx.body = {
        code: '1',
        msg: '测试成功',
    }
})

router.post('/refresh', async (ctx) => {
    const { refresh_token } = ctx.request.body;
    // 校验refresh_token是否合法
    const decoded = refreshVerify(refresh_token);
    if (decoded.id) {
        // console.log(decoded);
        const data = {
            id: decoded.id,
            username: decoded.username,
            password: decoded.password,
            create_time: decoded.create_time,
        }
        // 合法
        // 生成新的短token
        const access_token = sign(data, '1h');
        // 生成新的长token
        const refresh_token = sign(data, '7d');
        ctx.body = {
            code: '1',
            msg: 'token刷新成功',
            access_token: access_token,
            refresh_token: refresh_token,
        }
    } else {
        ctx.status = 416;
        ctx.body = {
            code: '0',
            msg: '登录失效，请重新登录',
        }
    }
})

// 注册接口
router.post('/register', async (ctx) => {
    try {
        const { username, password, nickname } = ctx.request.body;
        console.log(username, password, nickname);

        // // 校验参数
        // if (password !== confirmPassword) {
        //     ctx.body = {
        //         code: '0',
        //         msg: '两次密码不一致',
        //     }
        //     return;
        // }
        // 校验账号是否存在
        let res = await userLogin(username, password);
        if (res.length) {
            ctx.body = {
                code: '0',
                msg: '账号已存在',
            }
            return;
        }
        // 注册账号
        let registerRes = await register({ username, password, nickname, create_time: Date.now() });
        if (registerRes) {
            ctx.body = {
                code: '1',
                msg: '注册成功',
            }
        } else {
            ctx.body = {
                code: '0',
                msg: '注册失败',
            }
        }
    } catch (err) {
        ctx.body = {
            code: '-1',
            msg: '服务器异常',
            data: err.message
        }
    }
})


module.exports = router